package org.example.rzfx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.rzfx.dto.Result;
import org.example.rzfx.entity.*;
import org.example.rzfx.mapper.*;
import org.example.rzfx.service.DashboardService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Dashboard统计控制器
 */
@RestController
@RequestMapping("/api/dashboard")
@CrossOrigin
public class DashboardController {
    
    @Resource
    private LogMapper logMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private AlarmMapper alarmMapper;
    
    @Resource
    private LogSourceMapper logSourceMapper;
    
    @Resource
    private CollectMonitorMapper collectMonitorMapper;
    
    @Resource
    private DashboardService dashboardService;
    
    /**
     * 获取Dashboard概览数据
     */
    @GetMapping("/overview")
    public Result<Map<String, Object>> getDashboardOverview() {
        Map<String, Object> result = new HashMap<>();
        
        // 今日日志总数
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LambdaQueryWrapper<Log> todayLogWrapper = new LambdaQueryWrapper<>();
        todayLogWrapper.ge(Log::getCreateTime, todayStart);
        long todayLogCount = logMapper.selectCount(todayLogWrapper);
        result.put("todayLogCount", todayLogCount);
        
        // 今日错误日志数
        LambdaQueryWrapper<Log> todayErrorWrapper = new LambdaQueryWrapper<>();
        todayErrorWrapper.ge(Log::getCreateTime, todayStart)
                        .eq(Log::getLogLevel, "ERROR");
        long todayErrorCount = logMapper.selectCount(todayErrorWrapper);
        result.put("todayErrorCount", todayErrorCount);
        
        // 未处理告警数
        LambdaQueryWrapper<Alarm> unhandledAlarmWrapper = new LambdaQueryWrapper<>();
        unhandledAlarmWrapper.eq(Alarm::getStatus, 0);
        long unhandledAlarmCount = alarmMapper.selectCount(unhandledAlarmWrapper);
        result.put("unhandledAlarmCount", unhandledAlarmCount);
        
        // 今日新增告警数
        LambdaQueryWrapper<Alarm> todayAlarmWrapper = new LambdaQueryWrapper<>();
        todayAlarmWrapper.ge(Alarm::getAlarmTime, todayStart);
        long todayAlarmCount = alarmMapper.selectCount(todayAlarmWrapper);
        result.put("todayAlarmCount", todayAlarmCount);
        
        // 活跃采集源数
        LambdaQueryWrapper<LogSource> activeSourceWrapper = new LambdaQueryWrapper<>();
        activeSourceWrapper.eq(LogSource::getStatus, 1);
        long activeSourceCount = logSourceMapper.selectCount(activeSourceWrapper);
        result.put("activeSourceCount", activeSourceCount);
        
        // 总采集源数
        long totalSourceCount = logSourceMapper.selectCount(null);
        result.put("totalSourceCount", totalSourceCount);
        
        // 在线用户数（这里简化处理，实际应该从Redis或Session中获取）
        long onlineUserCount = userMapper.selectCount(null);
        result.put("onlineUserCount", onlineUserCount);
        
        // 系统健康状态
        result.put("systemHealth", "GOOD");
        
        // 最近24小时日志趋势
        LocalDateTime last24Hours = LocalDateTime.now().minusHours(24);
        List<Map<String, Object>> logTrend = logMapper.statLogTrend(
            last24Hours.toString(), 
            LocalDateTime.now().toString()
        );
        result.put("last24HoursLogTrend", logTrend);
        
        // 采集成功率
        List<CollectMonitor> monitors = collectMonitorMapper.selectList(null);
        long totalSuccess = monitors.stream().mapToLong(CollectMonitor::getSuccessCount).sum();
        long totalFail = monitors.stream().mapToLong(CollectMonitor::getFailCount).sum();
        double successRate = totalSuccess + totalFail > 0 
            ? (double) totalSuccess / (totalSuccess + totalFail) * 100 
            : 0;
        result.put("collectSuccessRate", String.format("%.2f", successRate));
        
        return Result.success(result);
    }
    
    /**
     * 获取系统统计数据
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics(@RequestParam(required = false, defaultValue = "7") Integer days) {
        Map<String, Object> result = new HashMap<>();
        
        // 总日志数
        long totalLogCount = logMapper.selectCount(null);
        result.put("totalLogCount", totalLogCount);
        
        // 总用户数
        long totalUserCount = userMapper.selectCount(null);
        result.put("totalUserCount", totalUserCount);
        
        // 总告警数
        long totalAlarmCount = alarmMapper.selectCount(null);
        result.put("totalAlarmCount", totalAlarmCount);
        
        // 总采集源数
        long totalSourceCount = logSourceMapper.selectCount(null);
        result.put("totalSourceCount", totalSourceCount);
        
        // 根据天数计算时间范围
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        LocalDateTime endTime = LocalDateTime.now();
        
        // 日志级别分布
        List<Map<String, Object>> levelDist = logMapper.statLogLevelDistribution(
            startTime.toString(), 
            endTime.toString()
        );
        result.put("logLevelDistribution", levelDist);
        
        // 系统类型分布
        List<Map<String, Object>> systemDist = logMapper.statSystemDistribution(
            startTime.toString(), 
            endTime.toString()
        );
        result.put("systemTypeDistribution", systemDist);
        
        // 日志趋势
        List<Map<String, Object>> logTrend = logMapper.statLogTrend(
            startTime.toString(),
            endTime.toString()
        );
        result.put("logTrend", logTrend);
        
        return Result.success(result);
    }
    
    /**
     * 获取告警统计
     */
    @GetMapping("/alarm-statistics")
    public Result<Map<String, Object>> getAlarmStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        LocalDateTime last7Days = LocalDateTime.now().minusDays(7);
        
        // 7天内告警总数
        LambdaQueryWrapper<Alarm> last7DaysWrapper = new LambdaQueryWrapper<>();
        last7DaysWrapper.ge(Alarm::getAlarmTime, last7Days);
        long last7DaysCount = alarmMapper.selectCount(last7DaysWrapper);
        result.put("last7DaysAlarmCount", last7DaysCount);
        
        // 7天内已处理告警数
        LambdaQueryWrapper<Alarm> handledWrapper = new LambdaQueryWrapper<>();
        handledWrapper.ge(Alarm::getAlarmTime, last7Days)
                     .eq(Alarm::getStatus, 1);
        long handledCount = alarmMapper.selectCount(handledWrapper);
        result.put("handledAlarmCount", handledCount);
        
        // 处理率
        double handleRate = last7DaysCount > 0 
            ? (double) handledCount / last7DaysCount * 100 
            : 0;
        result.put("alarmHandleRate", String.format("%.2f", handleRate));
        
        return Result.success(result);
    }
    
    /**
     * 清除Dashboard缓存
     */
    @DeleteMapping("/cache")
    public Result<Void> clearCache() {
        dashboardService.clearDashboardCache();
        return Result.success("Dashboard缓存已清除", null);
    }
}

